import router from './router';
import store from './store';
import NProgress from 'nprogress'; // Progress 进度条
import 'nprogress/nprogress.css'; // Progress 进度条样式
import {Message} from 'element-ui';
import {getToken} from '@/utils/auth'; // 验权
import {setTitle} from '@/utils/util'; // 设置浏览器头部标题
import {dynamicRouterMap} from '@/router';
import {getAccount} from "./utils/auth";

// permission judge function
function hasPermission(roles, permissionRoles) {
  if (roles.indexOf('admin') >= 0) return true; // admin permission passed directly
  if (!permissionRoles) return true;
  return roles.some(role => permissionRoles.indexOf(role) >= 0)
}

/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param routeNames
 * @param route
 */
function hasRoutePermission(routeNames, route) {
  if (route.meta && route.meta.title) {
    return routeNames.indexOf(route.meta.title) !== -1
  }
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param routeNames
 */
function routeFilterAsyncRouter(asyncRouterMap, routeNames) {
  return asyncRouterMap.filter(route => {
    if (hasRoutePermission(routeNames, route)) {
      if (route.children && route.children.length) {
        route.children = routeFilterAsyncRouter(route.children, routeNames)
      }
      return true
    }
    return false
  })
}

const whiteList = ['/login']; // 不重定向白名单
router.beforeEach((to, from, next) => {
  NProgress.start();
  if (getToken()) {
    /* has token*/
    if (store.getters.isLock && to.path !== '/lock') {
      next({
        path: '/lock'
      });
      NProgress.done()
    } else if (to.path === '/login') {
      next({path: '/'});
      NProgress.done() // if current page is dashboard will not trigger	afterEach hook, so manually handle it
    } else {
      if (store.getters.roles.length === 0) {
        store.dispatch('GetInfo').then(res => { // 拉取用户信息
          let account = getAccount();
          if (account.indexOf('test') !== -1) {

          } else {
            let asyncRouterMap = routeFilterAsyncRouter(dynamicRouterMap, res.data.routes);
            router.options.routes = asyncRouterMap;
            router.addRoutes(asyncRouterMap); // 动态添加可访问路由表
          }
          next();
        }).catch((err) => {
          store.dispatch('FedLogOut').then(() => {
            Message.error(err || 'Verification failed, please login again');
            next({path: '/'})
          })
        })
      } else {
        // 没有动态改变权限的需求可直接next() 删除下方权限判断 ↓
        if (hasPermission(store.getters.roles, to.meta.roles)) {
          next()//
        } else {
          next({path: '/401', replace: true, query: {noGoBack: true}})
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login');
      NProgress.done()
    }
  }
});

router.afterEach(() => {
  NProgress.done(); // 结束Progress
  setTimeout(() => {
    const browserHeaderTitle = store.getters.browserHeaderTitle;
    setTitle(browserHeaderTitle)
  }, 0)
});
